package cn.edu.hqu.javaee.web;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import cn.edu.hqu.javaee.domain.Personal;
import cn.edu.hqu.javaee.domain.User;
import cn.edu.hqu.javaee.repository.PersonalRepository;
import cn.edu.hqu.javaee.repository.UserRepository;

@Controller
@RequestMapping("/checkout")
@SessionAttributes("personal")
public class PersonalController {
	private PersonalRepository personalRepo;
	private UserRepository userRepo;
	
	public PersonalController(PersonalRepository personalRepo,UserRepository userRepo) {
		this.personalRepo = personalRepo;
		this.userRepo=userRepo;
	}
	@GetMapping("/personal")
	public String personal(Model model) {
		List<User> user = new ArrayList<>();
		userRepo.findAll().forEach(i -> user.add(i));
		model.addAttribute("user",user);
		System.out.println(user);
		return "personal";
	}

	@PostMapping
	public String processPersonal(@Valid Personal personal, Errors errors, SessionStatus sessionStatus)  {
		if (errors.hasErrors()) {
			return "personal";
		}
		personalRepo.save(personal);
		sessionStatus.setComplete();
	    System.out.println("personal"+personal);
		return "redirect:/result";
	}
}
